/**
 * 
 */
package it.battlehorse.scripting.mapping;

import it.battlehorse.scripting.IScriptingConstants;
import it.battlehorse.scripting.registry.IScriptingRegistry;
import it.battlehorse.scripting.registry.impl.BasicScriptingRegistry;

import org.eclipse.core.runtime.IConfigurationElement;


/**
 * Performs the mapping between a <code>scriptedView</code> and a traditional eclipse <code>view</code>.
 * @author battlehorse
 *
 */
public class ViewContributionMapper implements IContributionMapper, IScriptingConstants {
	
	/*
	 * (non-Javadoc)
	 * @see it.battlehorse.scripting.mapping.IContributionMapper#getContribution(org.eclipse.core.runtime.IConfigurationElement)
	 */
	public String getContribution(IConfigurationElement el) {
		
    	StringBuilder sb = new StringBuilder();
    	
    	sb.append("<plugin>");
    	sb.append("<extension point=\"org.eclipse.ui.views\">");
    	sb.append("<view "); 
    	appendAttribute(sb, el, "allowMultiple");
    	appendAttribute(sb, el, "category");
    	appendAttribute(sb, el, "name");
    	appendAttribute(sb, el, "icon");
    	appendAttribute(sb, el, "fastViewWidthRatio");
    	
    	// Id attribute
    	sb.append(" id=\"").append(getContributionId(el)).append("\" ");
    	
    	// Class attribute
    	sb.append(" class=\"it.battlehorse.scripting.view.ScriptProxyView\"");    	    	
    	
    	sb.append("/>");
    	sb.append("</extension>");
    	sb.append("</plugin>");   	
		return sb.toString();    	
	}
	
	/*
	 * (non-Javadoc)
	 * @see it.battlehorse.scripting.mapping.IContributionMapper#getContributionId(org.eclipse.core.runtime.IConfigurationElement)
	 */
	public String getContributionId(IConfigurationElement el) {
		return el.getAttribute("id") + ".autoView";
	}
	
	/*
	 * (non-Javadoc)
	 * @see it.battlehorse.scripting.mapping.IContributionMapper#updateScriptingRegistry(it.battlehorse.scripting.registry.IScriptingRegistry, org.eclipse.core.runtime.IConfigurationElement)
	 */
	public void updateScriptingRegistry(IScriptingRegistry registry, IConfigurationElement el) {
		BasicScriptingRegistry basicReg = (BasicScriptingRegistry) registry;
		
		IConfigurationElement scriptElement = el.getChildren(EL_SCRIPT)[0];
		basicReg.put(
				getContributionId(el), 
				scriptElement.getAttribute("id"), 
				scriptElement.getAttribute("uri"), 
				scriptElement.getAttribute("extension"),
				el.getNamespaceIdentifier(),
				"true".equals(scriptElement.getAttribute("modal")));
		
	}
	
	private void appendAttribute(StringBuilder sb, IConfigurationElement el, String attribute) {
		if (el.getAttribute(attribute) != null)
			sb.append(" ").append(attribute).append("=\"").append(el.getAttribute(attribute)).append("\" ");
	}

}
